package server.forms;


import javax.servlet.http.HttpServletRequest;

import commons.Manager;
import commons.exceptions.PasswordException;

/**
 * Class used to edit the passwords
 * @author Romain Pellerin
 */
public final class PasswordsForm {

	private static final String PWD_OK	= "Password has been updated.";
	
	private String admin_result;
	private String admin_error;
	private String guest_result;
	private String guest_error;
	/**
	 * Change the passwords send via a POST request
	 * @param request The HTTP request
	 */
	public void changePwds(HttpServletRequest request) {
		String currentAdminPassword =	getRequestValue(request, "currentAdminPassword");
		String newAdminPassword =		getRequestValue(request, "newAdminPassword");
		String currentGuestPassword =	getRequestValue(request, "currentGuestPassword");
		String newGuestPassword =		getRequestValue(request, "newGuestPassword");
		
		if (newAdminPassword != null) {
			try {
				Manager.getInstance().changeAdminPassword(currentAdminPassword, newAdminPassword);
				admin_result = PWD_OK;
			} catch (PasswordException e) {
				admin_error = e.getMessage();
			}
		}
		if (newGuestPassword != null) {
			try {
				Manager.getInstance().changeGuestPassword(currentGuestPassword, newGuestPassword);
				guest_result = PWD_OK;
			} catch (PasswordException e) {
				guest_error = e.getMessage();
			}
		}
	}
	
	/**
	 * Get the message result if the admin's password has been successfully changed
	 * @return The message or null if there is none
	 */
	public String getAdmin_result() {
		return admin_result;
	}

	/**
	 * Get the error that may have occured while changing admin's password
	 * @return The error or null if there is none
	 */
	public String getAdmin_error() {
		return admin_error;
	}

	/**
	 * Get the message result if the guest's password has been successfully changed
	 * @return The message or null if there is none
	 */
	public String getGuest_result() {
		return guest_result;
	}

	/**
	 * Get the error that may have occured while changing guest's password
	 * @return The error or null if there is none
	 */
	public String getGuest_error() {
		return guest_error;
	}

	/**
	 * Method used to retriveve a specific value from an HTTP request
	 * @param request The HTTP request
	 * @param fieldName The fieldname searched
	 * @return The value found, or null if <code>fieldName</code> isn't existing
	 */
	private static String getRequestValue(HttpServletRequest request, String fieldName) {
		String val = request.getParameter(fieldName);
		if (val == null || val.trim().length() == 0) {
			return null;
		} else {
			return val;
		}
	}
}
